#!/usr/bin/python3

import _thread
import time
import threading
import socket
import cv2
import numpy as np
from PIL import Image
import sys
import codecs
import struct

sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
print("socket start....")
receive_picture = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 第一步：初始化socket
send_msg = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 第一步：初始化socket

receive_picture.bind(('127.0.0.1', 9000))  # 第二步：绑定端口
send_msg.bind(('127.0.0.1', 9001))  # 第二步：绑定端口

receive_picture.listen(5)  # 第三步：监听端口
send_msg.listen(5)  # 第三步：监听端口

print("waiting msg....")
receive_picture_conn, receive_picture_client_add = receive_picture.accept()  # 第四步：接收客户端的connect连接请求
send_msg_conn, send_msg_client_add = send_msg.accept()  # 第四步：接收客户端的connect连接请求

height = 960
width = 1280
fps = 30
threadLock = threading.Lock()
threads = []
send_data = [1.1111, 2.1231231, 3.1231, 4.12312, 5.123131, 6.123131, 7.1231232]


class MyThread(threading.Thread):
    def __init__(self, thread_func, args, name):
        threading.Thread.__init__(self)
        # self.threadID = thread_id
        self.name = name
        self.func = thread_func
        self.args = args
        # self.counter = counter

    def get_result(self):
        return self.res

    def run(self):
        print("开启线程： " + self.name)
        # 获取锁，用于线程同步
        # threadLock.acquire()
        # 执行函数
        self.res = self.func(*self.args)
        # 释放锁，开启下一个线程
        # threadLock.release()


def float_to_bytes(f):
    bs = struct.pack("f", f)
    return bs
    # return (bs[3], bs[2], bs[1], bs[0])


send_data_byte = bytes(0)
for i in range(len(send_data)):
    send_data_byte_buffer = float_to_bytes(send_data[i])
    send_data_byte += send_data_byte_buffer


# send_thread = MyThread("send")
def send_msg():
    print("send msg....")
    while True:
        try:
            send_msg_conn.send(send_data_byte)
        except ConnectionResetError:
            break


def disp_image():
    print("receive msg....")
    while True:
        try:
            data = receive_picture_conn.recv(4915200)  # 第五步：接收客户端传来的数据信息
            # data = struct.unpack('3686400i', data)
            # data = data.decode('utf-16')
            # print(data[2])
            # # data = data.split(b' ')
            # print(data[0])
            if len(data) == 4915200:
                print("received msg length:", len(data))
                img = Image.frombuffer('RGBA', (width, height), data)
                image = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
                image = cv2.flip(image, 0)
                cv2.imshow('1', image)
                cv2.waitKey(2)
                # img.show()
                # for index in range(len(data)):
                #     data2 = int.from_bytes(data[index], byteorder="big", signed=False)
                #     print(data2)
                # rgbaimg = np.array([i for i in data])

                # rgbaimg = np.array(data)  # .astype(np.uint8).reshape([1280, 720, 4])
                # rgbaimg = ord(rgbaimg)
                # print(rgbaimg.dtype)
                # rgbaimg = rgbaimg.astype(np.uint8)
                # print(rgbaimg)
                # cv2.imshow("rgba", rgbaimg)
                pass
                # conn.send(data.upper())  # 第六步：给客户端回复信息
            else:
                break
        except ConnectionResetError:
            break


receive_thread = MyThread(disp_image, (), "receive")
send_thread = MyThread(send_msg, (), "send")

# 启动线程
receive_thread.start()
send_thread.start()

# 等待线程结束
receive_thread.join()
send_thread.join()

# while 1:
#     pass

# disp_image()
# try:
#     _thread.start_new_thread(disp_image, ())
# except():
#     print("error,start thread error!!")
#
# while 1:
#     pass
# 传输数据关闭
# conn.close()  # 第七步：传输数据关闭
